using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

[System.Serializable]
public class Wu_GeneralInfo
{
    public string generalName;     // 将军名称
    public int health;             // 将军生命值
    public bool is_attacking;      // 是否正在战斗
    public bool is_arrive;         // 是否到达目的地
    public int infantryAccount;    // 步兵数量
    public int archerAccount;      // 弓箭手数量
    public int cavalryAccount;     // 骑兵数量
    public string currentPosition; // 当前位置坐标
    public string targetPosition;  // 目标位置坐标
    public string formation;       // 阵型
    public string activity;        // 行为
}

public class Wu_General_Manager : MonoBehaviour
{
    // 单例模式
    public static Wu_General_Manager Instance { get; private set; }

    // 所有吴国将军

    [SerializeField] private SunCe sunCe;
    [SerializeField] private SunShangXiang sunShangXiang;
    [SerializeField] private LuXun luXun;
    [SerializeField] private GanNing ganNing;
    // 根据需要添加其他将军

    // 导出频率（秒）
    [SerializeField] private float exportInterval = 5f;

    // 导出路径
    private string exportFolderPath;
    private string exportFilePath;

    void Awake()
    {
        // 实现单例模式
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (Instance != this)
        {
            Destroy(gameObject);
        }

        // 设置导出路径
        exportFolderPath = Path.Combine(Application.dataPath, "Scripts/Wu_test/Wu/Wu_Information");
        exportFilePath = Path.Combine(exportFolderPath, "Wu_GeneralInfo.json");
    }

    void Start()
    {
        // 初始化时查找所有将军组件（如果没有在Inspector中设置）
        if (sunCe == null) sunCe = FindObjectOfType<SunCe>();
        if (sunShangXiang == null) sunShangXiang = FindObjectOfType<SunShangXiang>();
        if (luXun == null) luXun = FindObjectOfType<LuXun>();
        if (ganNing == null) ganNing = FindObjectOfType<GanNing>();

        // 不再自动启动导出协程，由Wei_Information_Manager控制导出时机
        // StartCoroutine(ExportGeneralsInfoRoutine());

        Debug.Log("吴国将军管理器已初始化，等待统一信息管理器进行导出");
    }

    // 定时导出将军信息的协程
    private IEnumerator ExportGeneralsInfoRoutine()
    {
        while (true)
        {
            ExportGeneralsInfo();
            yield return new WaitForSeconds(exportInterval);
        }
    }

    // 手动触发导出将军信息（已废弃，请使用ExportGeneralsInfoToFile来指定准确的文件路径）
    public void ExportGeneralsInfo()
    {
        Debug.LogWarning("ExportGeneralsInfo方法已废弃，请使用ExportGeneralsInfoToFile方法并指定文件路径。不再生成固定名称的文件。");

        // 不再生成固定名称的文件，而是记录一下当前将军状态
        List<Wu_GeneralInfo> generalsInfo = new List<Wu_GeneralInfo>();

        // 检查将军状态并记录日志
        if (sunCe != null && sunCe.health > 0)
        {
            Debug.Log($"将军 {sunCe.generalName} 健康值: {sunCe.health}");
        }

        if (sunShangXiang != null && sunShangXiang.health > 0)
        {
            Debug.Log($"将军 {sunShangXiang.generalName} 健康值: {sunShangXiang.health}");
        }

        if (luXun != null && luXun.health > 0)
        {
            Debug.Log($"将军 {luXun.generalName} 健康值: {luXun.health}");
        }

        if (ganNing != null && ganNing.health > 0)
        {
            Debug.Log($"将军 {ganNing.generalName} 健康值: {ganNing.health}");
        }

        if ((sunCe == null || sunCe.health <= 0) &&
            (sunShangXiang == null || sunShangXiang.health <= 0) &&
            (luXun == null || luXun.health <= 0) &&
            (ganNing == null || ganNing.health <= 0))
        {
            Debug.LogWarning("没有存活的吴国将军！");
        }
    }

    // 导出将军信息到指定文件路径
    public void ExportGeneralsInfoToFile(string filePath)
    {
        List<Wu_GeneralInfo> generalsInfo = new List<Wu_GeneralInfo>();

        // 检查孙坚是否存在并添加到将军列表
        Wu_ZhuGong sunCe = FindObjectOfType<Wu_ZhuGong>();
        if (sunCe != null && sunCe.health > 0)
        {
            Wu_GeneralInfo info = new Wu_GeneralInfo
            {
                generalName = sunCe.generalName,
                health = sunCe.health,
                is_attacking = sunCe.is_attacking,
                is_arrive = sunCe.is_arrive,
                infantryAccount = sunCe.infantryAccount,
                archerAccount = sunCe.archerAccount,
                cavalryAccount = sunCe.cavalryAccount,
                currentPosition = sunCe.currentPosition,
                targetPosition = sunCe.targetPosition,
                formation = sunCe.formation,
                activity = sunCe.activity
            };
            generalsInfo.Add(info);
            Debug.Log($"已添加孙坚信息：健康值: {sunCe.health}, 目标: {sunCe.targetPosition}, 活动: {sunCe.activity}");
        }

        // 检查孙尚香是否存活
        if (sunShangXiang != null && sunShangXiang.health > 0)
        {
            Wu_GeneralInfo info = new Wu_GeneralInfo
            {
                generalName = sunShangXiang.generalName,
                health = sunShangXiang.health,
                is_attacking = sunShangXiang.is_attacking,
                is_arrive = sunShangXiang.is_arrive,
                infantryAccount = sunShangXiang.infantryAccount,
                archerAccount = sunShangXiang.archerAccount,
                cavalryAccount = sunShangXiang.cavalryAccount,
                currentPosition = sunShangXiang.currentPosition,
                targetPosition = sunShangXiang.targetPosition,
                formation = sunShangXiang.formation,
                activity = sunShangXiang.activity
            };
            generalsInfo.Add(info);
        }

        // 检查陆逊是否存活
        if (luXun != null && luXun.health > 0)
        {
            Wu_GeneralInfo info = new Wu_GeneralInfo
            {
                generalName = luXun.generalName,
                health = luXun.health,
                is_attacking = luXun.is_attacking,
                is_arrive = luXun.is_arrive,
                infantryAccount = luXun.infantryAccount,
                archerAccount = luXun.archerAccount,
                cavalryAccount = luXun.cavalryAccount,
                currentPosition = luXun.currentPosition,
                targetPosition = luXun.targetPosition,
                formation = luXun.formation,
                activity = luXun.activity
            };
            generalsInfo.Add(info);
        }

        // 检查甘宁是否存活
        if (ganNing != null && ganNing.health > 0)
        {
            Wu_GeneralInfo info = new Wu_GeneralInfo
            {
                generalName = ganNing.generalName,
                health = ganNing.health,
                is_attacking = ganNing.is_attacking,
                is_arrive = ganNing.is_arrive,
                infantryAccount = ganNing.infantryAccount,
                archerAccount = ganNing.archerAccount,
                cavalryAccount = ganNing.cavalryAccount,
                currentPosition = ganNing.currentPosition,
                targetPosition = ganNing.targetPosition,
                formation = ganNing.formation,
                activity = ganNing.activity
            };
            generalsInfo.Add(info);
        }

        // 检查孙策是否存活
        if (sunCe != null && sunCe.health > 0)
        {
            Wu_GeneralInfo info = new Wu_GeneralInfo
            {
                generalName = sunCe.generalName,
                health = sunCe.health,
                is_attacking = sunCe.is_attacking,
                is_arrive = sunCe.is_arrive,
                infantryAccount = sunCe.infantryAccount,
                archerAccount = sunCe.archerAccount,
                cavalryAccount = sunCe.cavalryAccount,
                currentPosition = sunCe.currentPosition,
                targetPosition = sunCe.targetPosition,
                formation = sunCe.formation,
                activity = sunCe.activity
            };
            generalsInfo.Add(info);
        }

        // 如果没有存活的将军，则输出警告
        if (generalsInfo.Count == 0)
        {
            Debug.LogWarning("没有存活的吴国将军！");
            return;
        }

        // 生成指定路径的JSON文件
        ExportGeneralsList(generalsInfo, filePath);
    }

    // 将将军列表导出为JSON文件
    private void ExportGeneralsList(List<Wu_GeneralInfo> generalsInfo, string filePath)
    {
        // 生成JSON字符串
        string json = "[\n";
        for (int i = 0; i < generalsInfo.Count; i++)
        {
            var general = generalsInfo[i];
            json += $"  {{\n";
            json += $"    \"generalName\": \"{general.generalName}\",\n";
            json += $"    \"health\": {general.health},\n";
            json += $"    \"is_attacking\": {general.is_attacking.ToString().ToLower()},\n";
            json += $"    \"is_arrive\": {general.is_arrive.ToString().ToLower()},\n";
            json += $"    \"infantryAccount\": {general.infantryAccount},\n";
            json += $"    \"archerAccount\": {general.archerAccount},\n";
            json += $"    \"cavalryAccount\": {general.cavalryAccount},\n";
            json += $"    \"currentPosition\": \"{general.currentPosition}\",\n";
            json += $"    \"targetPosition\": \"{general.targetPosition}\",\n";
            json += $"    \"formation\": \"{general.formation}\",\n";
            json += $"    \"activity\": \"{general.activity}\"\n";
            json += $"  }}";

            if (i < generalsInfo.Count - 1)
            {
                json += ",\n";
            }
            else
            {
                json += "\n";
            }
        }
        json += "]";

        // 确保目录存在
        Directory.CreateDirectory(Path.GetDirectoryName(filePath));

        // 写入文件
        try
        {
            File.WriteAllText(filePath, json);
            Debug.Log($"成功导出吴国将军信息到: {filePath}");
        }
        catch (System.Exception e)
        {
            Debug.LogError($"导出将军信息时出错: {e.Message}");
        }

        // 刷新Asset数据库以显示新文件
#if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();
#endif
    }

    // 根据名称获取将军对象
    public Wu_GeneralInfo GetWu_GeneralInfoByName(string generalName)
    {
        if (sunCe != null && sunCe.health > 0 && sunCe.generalName == generalName)
        {
            return new Wu_GeneralInfo
            {
                generalName = sunCe.generalName,
                health = sunCe.health,
                is_attacking = sunCe.is_attacking,
                is_arrive = sunCe.is_arrive,
                infantryAccount = sunCe.infantryAccount,
                archerAccount = sunCe.archerAccount,
                cavalryAccount = sunCe.cavalryAccount,
                currentPosition = sunCe.currentPosition,
                targetPosition = sunCe.targetPosition,
                formation = sunCe.formation,
                activity = sunCe.activity
            };
        }
        else if (sunShangXiang != null && sunShangXiang.health > 0 && sunShangXiang.generalName == generalName)
        {
            return new Wu_GeneralInfo
            {
                generalName = sunShangXiang.generalName,
                health = sunShangXiang.health,
                is_attacking = sunShangXiang.is_attacking,
                is_arrive = sunShangXiang.is_arrive,
                infantryAccount = sunShangXiang.infantryAccount,
                archerAccount = sunShangXiang.archerAccount,
                cavalryAccount = sunShangXiang.cavalryAccount,
                currentPosition = sunShangXiang.currentPosition,
                targetPosition = sunShangXiang.targetPosition,
                formation = sunShangXiang.formation,
                activity = sunShangXiang.activity
            };
        }
        else if (luXun != null && luXun.health > 0 && luXun.generalName == generalName)
        {
            return new Wu_GeneralInfo
            {
                generalName = luXun.generalName,
                health = luXun.health,
                is_attacking = luXun.is_attacking,
                is_arrive = luXun.is_arrive,
                infantryAccount = luXun.infantryAccount,
                archerAccount = luXun.archerAccount,
                cavalryAccount = luXun.cavalryAccount,
                currentPosition = luXun.currentPosition,
                targetPosition = luXun.targetPosition,
                formation = luXun.formation,
                activity = luXun.activity
            };
        }
        else if (ganNing != null && ganNing.health > 0 && ganNing.generalName == generalName)
        {
            return new Wu_GeneralInfo
            {
                generalName = ganNing.generalName,
                health = ganNing.health,
                is_attacking = ganNing.is_attacking,
                is_arrive = ganNing.is_arrive,
                infantryAccount = ganNing.infantryAccount,
                archerAccount = ganNing.archerAccount,
                cavalryAccount = ganNing.cavalryAccount,
                currentPosition = ganNing.currentPosition,
                targetPosition = ganNing.targetPosition,
                formation = ganNing.formation,
                activity = ganNing.activity
            };
        }

        // 没有找到对应将军或将军已牺牲
        return null;
    }
}